package com.huimeilianchuang.controller;

import com.huimeilianchuang.pojo.User;
import com.huimeilianchuang.service.UserService;
import com.huimeilianchuang.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/hello")
    public String printhello() {
        return "hello lange";
    }

    //    微信登录
    @PostMapping("/loginByWechat")
    public Result loginByWechat(@RequestBody String openId) {
//        System.out.println(openId);
//        查询是否已经注册
        User user = userService.selectUserByOpenId(openId);
        if (user != null) {
            System.out.println(user);
            return Result.success(user);
        } else {
//            未注册，则注册并且登录
            User userAdd = new User();
            userAdd.setName("weixin_123");
            userAdd.setOpen_id(openId);
            userAdd.setHead_image("http://120.25.229.169:8082/images/defaultHeadImage.png");
            int res = userService.addUser(userAdd);
            if (res != 0) {
                User user2 = userService.selectUserByOpenId(openId);
                if (user2 != null) {
                    return Result.success(user2);
                } else {
                    return Result.error("500", "出错了！");
                }
            } else {
                return Result.error("500", "出错了！");
            }
        }
    }
}
